"use client";

import {
  Alert,
  AlertIcon,
  AlertTitle,
  Box,
  Button,
  Center,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Popover,
  PopoverArrow,
  PopoverBody,
  PopoverContent,
  PopoverTrigger,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import MacroNameEditor from "./MacroNameEditor";
import { MacroList } from "@/src/types/types.v1";
import MacroEditorV2 from "./MacroEditorV2";
import { useEffect, useState } from "react";
import _ from "lodash";
import { useTranslation } from "@/src/i18n";

function EditMacroList({
  macro,
  onChange,
  isOpen,
  onClose,
  checkName,
}: {
  macro: MacroList;
  onChange: (macro: MacroList) => void;
  isOpen: boolean;
  onClose: () => void;
  checkName: (name: string) => boolean;
}) {
  const [startRecord, setStartRecord] = useState(false);
  const { t } = useTranslation("");
  const cancleDlg = useDisclosure();
  const resetDlg = useDisclosure();

  const [editMacro, setEditMacro] = useState<MacroList>(_.cloneDeep(macro));

  const [isSave, setIsSave] = useState(false);
  const exitMacroBtn = () => {
    if (isSave) {
      setEditMacro({ ...macro });
      onClose();
    } else {
      cancleDlg.onOpen();
    }
  };

  const saveMacroList = () => {
    setIsSave(true);
    onChange(editMacro);
  };
  const toast = useToast();

  return (
    isOpen && (
      <div className="fixed w-screen h-screen top-0 left-0 z-50 bg-[#000000]/90 backdrop-blur-[32px]">
        <Box className="flex flex-col h-full">
          <Box className="flex justify-between px-[40px] py-4 border-b border-[#eeeeee] items-center">
            <MacroNameEditor
              name={editMacro.name}
              onChange={(name) => setEditMacro({ ...editMacro, name })}
              checkName={checkName}
              isDisabled={startRecord}
            />
            <Box className="flex justify-between gap-4">
              <Button
                variant={"outline"}
                className="!text-[#0066ff] !border-[#0066ff]"
                isDisabled={startRecord}
                onClick={() => {
                  saveMacroList();
                  toast({
                    title: t("saveSuccess"),
                    status: "success",
                    duration: 2000,
                    position: "top",
                    render: () => (
                      <Alert
                        status="success"
                        border={"1px solid #0066FF33"}
                        w={"fit-content"}
                        borderRadius={"4px"}
                      >
                        <AlertIcon className="!text-blue-1" />
                        <AlertTitle>{t("saveSuccess")}</AlertTitle>
                      </Alert>
                    ),
                  });
                }}
              >
                {t("save")}
              </Button>
              <Popover>
                {({ isOpen, onClose }) => (
                  <>
                    <PopoverTrigger>
                      <Button variant={"outline"} isDisabled={startRecord}>
                        {t("reset")}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="!right-[-40px]">
                      <PopoverArrow />
                      <PopoverBody>
                        {" "}
                        <p className="text-white-3 text-center py-6">
                          {t("resetMarco")}
                        </p>
                        <Box className="flex gap-2 justify-center">
                          <Button
                            className="!bg-red-600 !text-white !px-3  hover:!bg-red-600/90 !font-normal !rounded-[8px]"
                            onClick={() => {
                              setEditMacro({ ...editMacro, actions: [] });
                              onClose();
                              toast({
                                title: t("haveReset"),
                                status: "success",
                                duration: 2000,
                                position: "top",
                                render: () => (
                                  <Alert
                                    status="success"
                                    border={"1px solid #0066FF33"}
                                    w={"fit-content"}
                                    borderRadius={"4px"}
                                  >
                                    <AlertIcon className="!text-blue-1" />
                                    <AlertTitle>{t("haveReset")}</AlertTitle>
                                  </Alert>
                                ),
                              });
                            }}
                          >
                            {t("reset")}
                          </Button>
                          <Button
                            variant="ghost"
                            className="border border-gray-300 !font-normal !rounded-[8px]"
                            onClick={() => onClose()}
                          >
                            {t("cancel")}
                          </Button>
                        </Box>
                      </PopoverBody>
                    </PopoverContent>
                  </>
                )}
              </Popover>
              <Button
                variant={"outline"}
                isDisabled={startRecord}
                onClick={() => exitMacroBtn()}
              >
                {t("exitMacro")}
              </Button>
            </Box>
          </Box>
          <Box className="flex-1">
            {editMacro && (
              <MacroEditorV2
                macro={editMacro}
                onChange={(macro) => {
                  setEditMacro({ ...macro });
                }}
                onRecord={(start) => setStartRecord(start)}
              />
            )}
          </Box>
        </Box>

        <Modal
          isOpen={resetDlg.isOpen}
          onClose={resetDlg.onClose}
          size="sm"
          isCentered
        >
          <ModalOverlay />
          <ModalContent sx={{ color: "white" }}>
            <ModalBody>
              <p className="text-white-3 text-center pt-8">{t("resetMarco")}</p>
            </ModalBody>

            <ModalFooter className="gap-2">
              <Button
                variant={"unstyled"}
                className="!bg-red-600 !text-white !px-3  hover:!bg-red-600/90 !font-normal !rounded-[8px]"
                onClick={() => {
                  setEditMacro({ ...editMacro, actions: [] });
                  resetDlg.onClose();
                  toast({
                    title: t("haveReset"),
                    status: "success",
                    duration: 2000,
                    position: "top",
                    render: () => (
                      <Alert
                        status="success"
                        border={"1px solid #0066FF33"}
                        w={"fit-content"}
                        borderRadius={"4px"}
                      >
                        <AlertIcon className="!text-blue-1" />
                        <AlertTitle>{t("haveReset")}</AlertTitle>
                      </Alert>
                    ),
                  });
                }}
              >
                {t("reset")}
              </Button>
              <Button
                variant="ghost"
                className="border border-gray-300 !font-normal !rounded-[8px]"
                onClick={resetDlg.onClose}
              >
                {t("cancel")}
              </Button>
            </ModalFooter>
          </ModalContent>
        </Modal>
        <Modal
          isOpen={cancleDlg.isOpen}
          onClose={cancleDlg.onClose}
          size="sm"
          isCentered
        >
          <ModalOverlay />
          <ModalContent sx={{ color: "white" }}>
            <ModalHeader>{t("tips")}</ModalHeader>
            <ModalCloseButton />
            <ModalBody>
              <p className="text-white-3 text-center mb-2">{t("isSave")}</p>
            </ModalBody>

            <ModalFooter className="gap-2 !justify-center">
              <Button
                className="!bg-[#006BEE] !text-white !px-3 hover:!bg-[#0066FF]/90 !font-normal !rounded-[8px]"
                onClick={() => {
                  saveMacroList();
                  cancleDlg.onClose();
                  toast({
                    title: t("saveSuccess"),
                    status: "success",
                    duration: 2000,
                    position: "top",
                    render: () => (
                      <Alert
                        status="success"
                        border={"1px solid #0066FF33"}
                        w={"fit-content"}
                        borderRadius={"4px"}
                      >
                        <AlertIcon className="!text-blue-1" />
                        <AlertTitle>{t("saveSuccess")}</AlertTitle>
                      </Alert>
                    ),
                  });
                  onClose();
                }}
              >
                {t("saveExit")}
              </Button>
              <Button
                className="border border-blue-1 !text-blue-1 !bg-transparent !font-normal !rounded-[8px]"
                onClick={() => {
                  cancleDlg.onClose();
                  setEditMacro({ ...macro });
                  onClose();
                }}
              >
                {t("directExit")}
              </Button>
              <Button
                variant="ghost"
                className="border border-gray-300 !font-normal !rounded-[8px]"
                onClick={cancleDlg.onClose}
              >
                {t("cancel")}
              </Button>
            </ModalFooter>
          </ModalContent>
        </Modal>
      </div>
    )
  );
}

export default EditMacroList;
